<?php
/**
 * Created by yusheng
 * Date: 2018/6/23
 * Time: 下午5:57
 */

namespace App\Observers;

use App\Models\Coupon;
use App\Models\DispatchFreeLog;

class DispatchFreeLogObserver
{
    public function created(DispatchFreeLog $dispatchFreeLog)
    {
        $team = $dispatchFreeLog->teamLeader->team;
        if ($dispatchFreeLog->num > $team->free_times) {
            $dispatchFreeLog->delete();
        } else {
            //减少团体免费数量
            $team->free_times -= $dispatchFreeLog->num;
            $team->save();
            //增加coupon
            for ($i = 1; $i <= $dispatchFreeLog->num; $i ++) {
                Coupon::create([
                    'user_id' => $dispatchFreeLog->user->id,
                    'name' => $team->name . '免费券',
                    'type' => 'free',
                ]);
            }
        }
    }

}